<template>
  <div style="width:400px; border:2px solid #69f;">
    <p><el-button @click="uploadNow" :disabled="!localUrl" type="primary">现在上传</el-button></p>

    <el-upload
      list-type="picture-card"
      ref="upload"
      :action="uploadRemoteUrl"
      :on-change="imgSaveToUrl"
      class="avatar-uploader"
      :auto-upload="notAuto"
      :data="qiniuData"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
    >
      <i v-if="!localUrl" class="el-icon-plus"></i>
      <img v-else width="100%" :src="localUrl" alt="" />
    </el-upload>
  </div>
</template>

<script>
import Qs from "qs";
export default {
  props: {
    icon: { type: String },
  },
  data() {
    return {
      notAuto: false,
      dialogVisible: false,
      localUrl: "",
      dialogImageUrl: "",
      imageUrl: "", //传给后台的src
      uploadRemoteUrl: "http://upload.qiniup.com", //七牛云的上传地址(华东) 详细参考：https://developer.qiniu.com/kodo/1671/region-endpoint-fq
      qiniuData: {
        key: "", // 图片名字处理--在下文有对应方法处理 可全文搜索 key 查看
        token:
          "BX8KoFSjbcxdiJ3qUUtMbE5LVhzK3fkLowqzq-QR:yyFQ6wvYRrPf-HecOvzNoFfqUdY=:eyJzY29wZSI6ImNvbW1vbi1hc3NldHMiLCJkZWFkbGluZSI6MTY0NTIxMTEyMH0=", // 后台获取token
      },
      qiniuAddr: "http://xcaipu.cn/",
      //七牛云的图片外链地址
      // 通常情况是域名绑定出了问题，你可以查看下你绑定的域名这个域名是否有解析到，域名完成绑定后，需要将域名解析到七牛的 cname 地址
    };
  },
  mounted() {
    this.getQiniuToken();
    
  },
  methods: {
    
    uploadNow() {
      this.$refs.upload.submit();
    },
    imgSaveToUrl(event) {
      console.log("改变了：", event);
      // 获取上传图片的本地URL，用于上传前的本地预览
      var URL = null;
      if (window.createObjectURL != undefined) {
        // basic
        URL = window.createObjectURL(event.raw);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(event.raw);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(event.raw);
      }
      // 转换后的地址为 blob:http://xxx/7bf54338-74bb-47b9-9a7f-7a7093c716b5
      this.localUrl = URL;
      this.dialogImageUrl = true; //呈现本地预览组件
      this.dialogVisible = true; //隐藏上传组件

      // 原文链接：https://blog.csdn.net/zrcj0706/article/details/103136634
    },
    handlePictureCardPreview(file) {
      console.log("file:", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(res) {
      console.log("上传成功：--", res,this);
      this.imageUrl = `${this.qiniuAddr}${res.key}`;
      // this.$emit("getFromChild", this.imageUrl);
      // 图片上传成功后，将图片地址传给后端保存
      
      // this.$forceUpdate()
      // 在下一个任务刷新
      this.$nextTick(()=>{
        this.localUrl = '';
      })
      this.saveImgFun(this.imageUrl);
      this.$message({
        message: '上传成功',
        type:'success'
      })
      console.log("this.localUrl:",this.localUrl)
    },
    async saveImgFun(url) {
      console.log("新图片地址：", url);
      const res = await this.$axios.post(
        "/api/saveImg",
        { url }
        // { headers: { "Content-Type": "application/json" } }
      );
      console.log("saveImgFun-res:", res);
      let timer = setTimeout(()=>{
        clearTimeout(timer)
        // 不能访问太快，服务器没反应过来
        this.$emit("update")
      }, 1000)
      // this.tableData=[]
      // if (res && res.data) {
      //   for (let i = 0; i < res.data.length; i++) {
      //     let one = { url: res.data[i], name: res.data[i] };
      //     this.tableData.push(one);
      //   }
      // }
    },
    
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // 自定义七牛云文件上传名称
      let now = Date.now() + "";
      this.qiniuData.key = `upload_pic_${now}_${file.name}`;

      return isJPG && isLt2M;
    },
    async getQiniuToken() {
      const res = await this.$axios.get("/api/token");
      console.log("token-res:", res);
      this.qiniuData.token = res.data;
    },
  },
};
</script>


<style scoped>
.title{
  text-align: left; padding: 10px; margin-top:15px; border-top: 1px solid #ddd;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>